const NoticeModel = require("../model/notice");
const BaseController = require("./base/base");
const Result = require("../utils/result");
class NoticeController extends BaseController {
  constructor() {
    super();
    this.key = "xiaohuai";
  }
  // 获取社团公告列表
  findNoticeList(req, res, next) {
    setTimeout(async () => {
      try {
        let { pagesize = 5, page = 1, notice_text = '', notice_type = '', creator = '' } = req.query;
        pagesize *= 1
        page *= 1
        let start = (page - 1) * pagesize;
        const _filter = { notice_text: { $regex: notice_text, $options: 'i' }, notice_type: { $regex: notice_type, $options: 'i' }, creator: { $regex: creator, $options: 'i' } }
        let list = await NoticeModel.find(_filter).limit(pagesize).skip(start)
        let total = await NoticeModel.countDocuments(_filter)
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 增加公告
  insert(req, res, next) {
    setTimeout(async () => {
      try {
        let { notice_text = '', notice_type = '', notice_state = 1, creator = '', add_time } = req.body;
        notice_state *= 1
        if (!notice_text) return res.json(Result.fail("公告标题不能为空"));
        const ret = await NoticeModel.create({ notice_text, notice_type, notice_state, creator, add_time });
        res.json(!ret._id ? Result.fail("添加失败") : Result.ok("添加成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 修改公告信息
  updateNotice(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await NoticeModel.updateOne({ _id: id }, req.body);
        console.log(ret);
        if (ret.matchedCount != 1) return res.json(Result.fail("修改失败", ret))
        res.json(Result.ok("修改成功", ret));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  // 删除公告
  delById(req, res, next) {
    setTimeout(async () => {
      try {
        const { id } = req.params;
        let ret = await NoticeModel.deleteOne({ _id: id });
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功", ret))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new NoticeController().resolve();